<?php

namespace app\beautiful\controller\miniapp\staff;

use app\BaseController;

use app\common\logic\SmsLogic;

use app\beautiful\logic\order\OrderLogic;

use app\beautiful\logic\printer\PrinterLogic;

use app\beautiful\model\member\MemberModel;

use app\beautiful\model\order\GoodsOrderItemModel;

use app\beautiful\model\order\GoodsOrderModel;

use app\beautiful\model\setting\SettingSmsModel;

use app\common\model\ShopDetailModel;
use app\stores\model\member\MemberLevelModel;
use think\facade\Db;



class Order extends BaseController{



    protected function initialize()

    {

        parent::initialize(); // TODO: Change the autogenerated stub

        if (!in_array(5, $this->request->staff->add_value_jurisdiction)) {

            $this->error('您没有订单管理的权限')->send();

            die();

        }

    }



    public function getGoodsOrderList(){

        $status = $this->request->param('status/d');

        $member_id=$this->request->param('member_id/d',0);

        $mobile=$this->request->param('mobile');

        $from_type=$this->request->param('from_type/d',1);

        $return = [];

        $where= [

            ['shop_id','=', $this->request->shopId],

            ['is_delete','=',0]

        ];

        $member_where=[

            ['shop_id','=',$this->request->shopId]

        ];

        if($member_id != 0){

            if(null !== $member = MemberModel::find($member_id)){

                $return['member']=[

                    'member_id'=>$member->member_id,

                    'mobile'=>$member->mobile,

                ];

            }

            $member_where[]=['member_id','=',$member_id];

        }else{

            if(!empty($mobile)){

                $member_where[]=['mobile','=',$mobile];

            }

        }
        if($this->request->from_type==2){
            $member_ids = MemberLevelModel::where($member_where)->column('member_id') ?? [];
        }else{
            $member_ids = MemberModel::where($member_where)->column('member_id') ?? [];
        }
        $where[]=['member_id','in',$member_ids];

        switch ($status){ //查询订单的状态

            case 0: // 待付款

                $where[] = ['status','=',1];

                break;

            case 1: //待发货

                $where[] = ['status','=',2];

                break;

            case 2: //待收货

                $where[] = ['status','=',3];

                break;

            case 3://待自提

                $where[] = ['status','=',4];

                break;

            case 4://已完成  取消的订单也在已完成里面

                $where[] = ['status','IN',[8,-1]];

                break;
            case 9://同城待配送

                $where[] = ['status','=',9];

                break;

        }

        $datas = GoodsOrderModel::with(['skus','member'=>function($query){

            $query->field('member_id,nick_name,mobile')->append(['hidden_mobile']);

        }])->where($where)

            ->json(['order_send_time'],true)

            ->field('order_id,order_sn,order_type,logistics_type,member_id,total_price,need_pay,integral_balance,coupon_money,youhui_balance,is_paid,status,add_time,order_send_time,
            
            receiving_name,receiving_mobile,receiving_address_province,receiving_address_city,receiving_address_county,receiving_address_info')

            ->limit($this->request->limit)

            ->page($this->request->page)

            ->order(['order_id'=>'desc'])

            ->select()->append(['order_time','djs_time','youhui'])

            ->toArray();

        $return['datas']=$datas;

        return $this->success($return);

    }



    public function detail()

    {

        $order_id = $this->request->param('order_id/d',0);

        if($order_id==0) return $this->error('订单不存在#1');

        if(null === $order = GoodsOrderModel::where(['order_id'=>$order_id])->json(['order_send_time'],true)->find()) return $this->error('订单不存在#2');

        if($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');

        if($order->is_delete != 0) return $this->error('订单不存在#4');

        if(!in_array($order->status,[2,3,4,8,9,10]))   return $this->error('该订单状态不能核销');

        if(null === $member = MemberModel::find($order->member_id)) return $this->error('订单不存在#5');

        if($this->request->from_type==2){
            $member_level = MemberLevelModel::where(['shop_id'=>$this->request->shopId,'member_id'=>$order->member_id,'is_delete'=>0])->find();
            if(empty($member_level)) return $this->error('订单不存在#8');
        }else{
            if($member->shop_id != $this->request->shopId) return $this->error('订单不存在#6');
        }



        $member->append(['hidden_mobile']);



        $items=GoodsOrderItemModel::where([

            ['shop_id','=',$this->request->shopId],

            ['order_id','=',$order_id]

        ])->field('*,goods_num as total_num')->select()->toArray();

        $total_num = GoodsOrderItemModel::where([

            ['shop_id','=',$this->request->shopId],

            ['order_id','=',$order_id]

        ])->sum('goods_num');

        if(empty($items)) return $this->error('订单不存在#7');



        $order->append(['add_time_format','pay_time_format','status_means','order_type_means','pay_type_mean']);



        $detail=[

            'order_id'=>$order->order_id,

            'order_sn'=>$order->order_sn,

            'logistics_type'=>$order->logistics_type,

            'freight_type'=>$order->freight_type,

            'add_time_format'=>$order->add_time_format,

            'order_type_means'=>$order->order_type_means,

            'order_type'=>$order->order_type,

            'status'=>$order->status,

            'status_means'=>$order->status_means,

            'need_pay'=>$order->need_pay,

            'pay_type'=>$order->pay_type,

            'pay_type_mean'=>$order->pay_type_mean,

            'pay_time_format'=>$order->pay_time_format,

            'receiving_name'=>$order->receiving_name,

            'receiving_mobile'=>$order->receiving_mobile,

            'receiving_address_province'=>$order->receiving_address_province,

            'receiving_address_city'=>$order->receiving_address_city,

            'receiving_address_county'=>$order->receiving_address_county,

            'receiving_address_info'=>$order->receiving_address_info,

            'total_price'=>$order->total_price,

            'youhui_balance'=>$order->youhui_balance,

            'freight'=>$order->freight,

            'coupon_money'=>$order->coupon_money,

            'integral_balance'=>$order->integral_balance,

            'member_name'=>$member->nick_name,

            'member_mobile'=>$member->mobile,

            'member_hidden_mobile'=>$member->hidden_mobile,

            'skus'=>$items,

            'total_num'=>$total_num,

            'order_send_time'=>$order->order_send_time

        ];



        return $this->success(['detail'=>$detail]);

    }



    public function cancelOrder()

    {

        $order_id=$this->request->param('order_id/d',0);

        if(empty($order_id)) return $this->error('订单不存在');

        $order=GoodsOrderModel::find($order_id);

        if(null === $order) $this->error('订单不存在');

        $params=[

            'member_id'=>$order->member_id,

            'order_id'=>$order_id,

        ];

        Db::startTrans();

        try{

            $order_logic = OrderLogic::init($this->request->shopId);

            $order_logic[$order->order_type]->cancelOrder($params);

            Db::commit();

            return $this->success('成功');

        } catch (\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function overGoods(){

        $order_id = $this->request->param('order_id/d',0);

        if($order_id==0) return $this->error('订单不存在#1');

        if(null === $order = GoodsOrderModel::find($order_id)) return $this->error('订单不存在#2');

        if($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');

        if($order->is_delete != 0) return $this->error('订单不存在#4');

        if($order->logistics_type != 1) $this->error('该订单无法完成');

        if($order->status !=3) return $this->error('该订单无法完成');

        $order->status=8;

        $order->save();

        return $this->success('订单已完成');

    }



    public function deliverGoods()

    {

        $order_id = $this->request->param('order_id/d',0);

        if($order_id==0) return $this->error('订单不存在#1');

        if(null === $order = GoodsOrderModel::find($order_id)) return $this->error('订单不存在#2');

        if($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');

        if($order->is_delete != 0) return $this->error('订单不存在#4');

        if($order->logistics_type != 1) $this->error('该订单无法发货');

        if($order->status !=2) return $this->error('该订单无法发货');



        if(null === $member = MemberModel::find($order->member_id)) return $this->error('订单不存在#5');



        $order->status=3;

        $order->save();



        //其他要补充的

        //发送短信给用户

        try{

            $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();

            if(null !== $sms_setting){



                if($sms_setting->order_deliver_notice_member==1){

                    $sms_logic= new SmsLogic();

                    $params=[

                        'id'=>(string)$order_id,

                    ];

                    $sms_logic->send($this->request->shopId,[$member->mobile],$params,'orderDeliverNoticeMember');

                }

            }

        }catch (\Exception $e){



        }



        return $this->success('发货成功');

    }
    public function writeOff()

    {

        $order_id = $this->request->param('order_id/d',0);

        if($order_id==0) return $this->error('订单不存在#1');

        if(null === $order = GoodsOrderModel::find($order_id)) return $this->error('订单不存在#2');

        if($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');

        if($order->is_delete != 0) return $this->error('订单不存在#4');

        if(!in_array($order->logistics_type,[2,3])) $this->error('该订单无法核销');

        if(!in_array($order->status,[4,9])) return $this->error('该订单无法核销');



        if(null === $member = MemberModel::find($order->member_id)) return $this->error('订单不存在#5');

        Db::startTrans();

        try{

            $order->status=8;

            $order->edit_time=date('Y-m-d H:i:s');

            $order->save();



            //其他要补充的

            //语音播报
            $item_order = GoodsOrderItemModel::where(['order_id'=>$order_id])->select();
            $detail = ShopDetailModel::where(['shop_id'=>$this->request->shopId])->find();
            foreach ($item_order as $k=>$v){
                $voice['msg'] = $v['goods_name'].'核销成功';
                $voice['sbx_id'] = $detail->sbx_id;
                sendvoice($voice);
            }

            //股东分红
            order_bonus($order_id,0);

            //发送短信给用户

            $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();

            if(null !== $sms_setting){



                if($sms_setting->order_write_off_notice_member==1){

                    $sms_logic= new SmsLogic();

                    $params=[

                        'id'=>(string)$order_id,

                    ];

                    $sms_logic->send($this->request->shopId,[$member->mobile],$params,'orderWriteOffNoticeMember');

                }

            }


            //打印机

            $printer_logic =new PrinterLogic($this->request->shopId);

            $printer_logic->print('orderWriteOff',$order->order_id);

            Db::commit();
            return $this->success('核销成功');
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }

    public function writeOffdandian()

    {

        $order_id = $this->request->param('order_id/d',0);

        if($order_id==0) return $this->error('订单不存在#1');

        if(null === $order = GoodsOrderModel::find($order_id)) return $this->error('订单不存在#2');

        if($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');

        if($order->is_delete != 0) return $this->error('订单不存在#4');

        if(!in_array($order->logistics_type,[2,3])) $this->error('该订单无法核销');

        if(!in_array($order->status,[4,9])) return $this->error('该订单无法核销');



        if(null === $member = MemberModel::find($order->member_id)) return $this->error('订单不存在#5');



        $order->status=8;

        $order->edit_time=date('Y-m-d H:i:s');

        $order->save();



        //其他要补充的

        //发送短信给用户

        try{
            //股东分红
            order_bonus($order_id,0);

            $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();

            if(null !== $sms_setting){



                if($sms_setting->order_write_off_notice_member==1){

                    $sms_logic= new SmsLogic();

                    $params=[

                        'id'=>(string)$order_id,

                    ];

                    $sms_logic->send($this->request->shopId,[$member->mobile],$params,'orderWriteOffNoticeMember');

                }

            }

        }catch (\Exception $e){



        }



        //打印机

        $printer_logic =new PrinterLogic($this->request->shopId);

        $printer_logic->print('orderWriteOff',$order->order_id);



        return $this->success('核销成功');

    }

}

